package com.example.xd.phone_album

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment

const val TYPE = "type"
const val TYPE_PICTURE = "type_picture"
const val TYPE_VIDEO = "type_video"
const val PERMISSION_CODE = 1


class PhoneActivity : AppCompatActivity() {
    var permission = arrayOf<String>(
        Manifest.permission.CAMERA,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_phone)
        if (hasPermission(this, permission)) {
            init()
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                ActivityCompat.requestPermissions(this, permission, PERMISSION_CODE)
            }
        }


    }

    private fun init() {
        val type = intent.getStringExtra(TYPE)
        when (type) {
            TYPE_PICTURE -> {
                initFirstFragment(TYPE_PICTURE)
            }
            TYPE_VIDEO -> {
                initFirstFragment(TYPE_VIDEO)
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSION_CODE) {
            if (hasPermission(this, permission)) {
                init()
            } else {
                toast(this, "没有权限")
                finish()
            }
        }
    }

    lateinit var currentFg: Fragment
    private fun initFirstFragment(callType: String) {
        when (callType) {
            TYPE_PICTURE -> {
                currentFg = FgFactory.getFragment(TYPE_PICTURE)
            }
            TYPE_VIDEO -> {
                currentFg = FgFactory.getFragment(TYPE_VIDEO)
            }
        }
        if (!currentFg.isAdded) {
            supportFragmentManager.beginTransaction().add(R.id.phone_fl, currentFg).commit()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
    }
}